<template>
	<el-dialog v-model="visible" :destroy-on-close="true" :width="800" top="5" :title="dialogData.title">
		<el-form ref="ruleFormRef" :rules="rules" :disabled="dialogData.isView" :model="dialogData.rowData"
			label-width="100px">
			<el-row>
				<el-col :span="24">
					<el-form-item label="业务选择" prop="deptId" clearable>
						<el-select v-model="dialogData.rowData!.businessId" @change="onChange" placeholder="请选择业务流程" style="width: 240px">
							<el-option v-for="item in businessList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="流程名称" prop="name" clearable>
						<el-input v-model="dialogData.rowData!.name" placeholder="请输入流程名称"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" v-show="!dialogData.isView" @click="handleSubmit">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="UserDialog">
import { ref, reactive } from 'vue';
import { ElMessage, FormInstance, FormRules, ElMessageBox } from 'element-plus';

import { getAllList } from '/@/api/workflow/business';

import rulesObj from './rules';

//验证规则
const rules = reactive<FormRules>(rulesObj);

const businessList = ref([])

//定义弹框props参数
interface DialogProps {
	title: string;
	isView: boolean;
	rowData?: any;
	apiUrl?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const visible = ref(false);
const dialogData = ref<DialogProps>({
	isView: false,
	title: '',
	rowData: null,
});

const onChange = (value:String) => {
	const business = businessList.value.find(u => u.id === value);
	if(business) {
		dialogData.value.rowData.name = business.name;
	}
}

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
	dialogData.value = params;
	//请求部门信息
	const res = await getAllList(null);
	if (res.code === 0) {
		businessList.value = res.data
	}
	visible.value = true;
};

const ruleFormRef = ref<FormInstance>();
// 提交数据（新增/编辑）
const handleSubmit = () => {
	ruleFormRef.value!.validate((valid) => {
		if (!valid) return;
		if (!dialogData.value.apiUrl) return;
		ElMessageBox.confirm(`确定${dialogData.value.title}吗?`, '提示', { type: 'warning' }).then(async () => {
			const res = await dialogData.value.apiUrl(dialogData.value.rowData);
			if (res) {
				ElMessage.success({ message: `${dialogData.value.title}用户成功！` });
				dialogData.value.getTableList && dialogData.value.getTableList();
				visible.value = false;
			}
		});
	});
};

defineExpose({
	acceptParams,
});
</script>
